<?php
namespace application\admin\model;
use think\Config;
use think\Request;

class User extends Base
{
    // 类型转换
    protected $type = [
        'age'       => 'integer',
        'sex'       => 'integer',
        'status'    => 'integer'
    ];

    // 验证规则
    protected $rule = [
        'nickname' => 'require|min:3',
        'password' => 'require',
        'email'    => 'require|email',
    ];

    // 自动完成
    protected $auto = ['login_time', 'login_ip'];
    protected $insert = ['create_time', 'modify_time'];
    protected $update = ['modify_time'];

    /**
     * 获取用户列表
     * @param array $params
     * @return array|false
     */
    public function getList($params = [])
    {
        $result     = [];
        $condition  = [];

        if( isset($params['status']) ) {
            $condition['status'] = intval($params['status']);
        }
        
        // 分页记录数
        if( isset($params['size']) )
            $size = intval($params['size']);
        else
            $size = Config::get('page_size');
        
        // 页数
        if( isset($params['page']) )
            $page = intval($params['page']) > 0 ? intval($params['page']) : 1;
        else
            $page = 1;

        $result = $this->where($condition)->page($page, $size)->select();

        return $result;
    }

    /**
     * 添加用户
     * @param $params
     */
    public function addItem($params)
    {
        $result = ['status'=>0, 'value'=>0, 'msg'=>'用户添加成功'];

        if($params)
        {
            if($this->data($params)->validate(true)->save()){
                $result['value'] = $this->id;
            }else{
                $result['status'] = 1;
                $result['msg'] = $this->getError();
            }
        }

        return $result;
    }

    // 修改器 - 创建时间
    protected function setCreateTimeAttr($value)
    {
        return time();
    }

    // 修改器 - 修改时间
    protected function setModifyTimeAttr($value)
    {
        return time();
    }

    // 修改器 - 登录时间
    protected function setLoginTimeAttr($value)
    {
        return time();
    }

    // 修改器 - 登录IP
    protected function setLoginIpAttr($value)
    {
        return Request::instance()->ip(1);
    }
}